package com.gwt.tirso.gymkhana.client;



import java.util.ArrayList;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwt.tirso.gymkhana.shared.DelistedException;
import com.gwt.tirso.gymkhana.shared.FieldVerifier;
import com.gwt.tirso.gymkhana.shared.IdGenerator;

public class CreationStep2 implements EntryPoint {

	private Label question0 = new Label();
	private Label note = new Label();
	private Label quest = new Label();
	private Label answer = new Label();
	private Label errorLabel = new Label();
	private TextBox textQuest = new TextBox();
	private TextBox textAnswer = new TextBox();
	private Button next = new Button();
	private Button cancel = new Button();
	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel buttonsPanel = new HorizontalPanel();
	private Gymkhana gymk = new Gymkhana();
	private ArrayList<Question> lq = new ArrayList<Question>();
	
	private Person author;

	private ILoginServiceAsync loginCon;

	@Override
	public void onModuleLoad() {
		
		loadCreationStep2();
				
	}

	private void loadCreationStep2() {
		// Labels
		question0.setText("Pregunta inicial");
		note.setText("*Esta pregunta la tendran todos los equipos al comienzo de la partida");
		quest.setText("Pregunta");
		answer.setText("Respuesta");
		

		textQuest.setFocus(true);

		// Buttons
		next.setText("Siguiente");
		cancel.setText("Cancelar");

		// mainPanel
		mainPanel.add(question0);
		mainPanel.add(note);
		mainPanel.add(quest);
		mainPanel.add(textQuest);
		mainPanel.add(answer);
		mainPanel.add(textAnswer);

		// buttonsPanel
		buttonsPanel.add(next);
		buttonsPanel.add(cancel);

		mainPanel.add(buttonsPanel);

		errorLabel.addStyleName("errorLabel");
		mainPanel.addStyleName("creationNext");
		RootPanel.get("creation").add(mainPanel);

		// initialize connection
		loginCon = ConnectionRpc.initRpcLogin();

		// Listen for mouse events on the acceptButton.
		next.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				loginCon.loginFromSessionServer(new AsyncCallback<Person>() {

					@Override
					public void onSuccess(Person result) {
						if (result == null) {
							Window.alert("Para acceder a la aplicación debe iniciar sesión");
							cancelStep();
						} else {
							Question q = receiveInfo();
							if (q == null) {
								mainPanel.add(errorLabel);
							} else {
								lq.add(q);
								step3();
							}
						}

					}

					@Override
					public void onFailure(Throwable caught) {
						String details = caught.getMessage();
				        if (caught instanceof DelistedException) {
				          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
				        }

				        errorLabel.setText("Error: " + details);
				        errorLabel.setVisible(true);

					}
				});
			}
		});

		cancel.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				cancelStep();
			}
		});	
	}

	// this method receive the question and save that for the next step
	public Question receiveInfo() {
		Question q = new Question();

		// question text
		String questT = textQuest.getText();
		if (!FieldVerifier.isValidName(questT)) {
			errorLabel.setText("Escriba una pregunta");
			return null;
		}
		q.setQuestionText(questT);

		// answer text
		String answT = textAnswer.getText();
		if (!FieldVerifier.isValidName(answT)) {
			errorLabel.setText("Escriba una respuesta");
			return null;
		}
		q.setAnswerText(answT);

		// is Initial
		q.setInitial(true);

		// code initial question
		q.setCode("0000");
		
		q.setId(IdGenerator.getInstance().getKey());
		
		q.setGymkId(gymk.getId());

		return q;

	}

	// this method is used in step1 to send Gymkhana information
	public void setGymk(Gymkhana gymk) {
		this.gymk = gymk;
	}

	private void step3() {
		CreationStep3 p = new CreationStep3();
		p.onModuleLoad();
		RootPanel.get("creation").remove(mainPanel);

		// gymkhana´s info
		p.setGymk(gymk);
		p.setLq(lq);
		p.setNq(gymk.getnQuestions() - 1);
		p.setAuthor(author);
	}

	private void cancelStep() {
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		RootPanel.get("creation").remove(mainPanel);
	}

	public void setAuthor(Person p) {
		this.author = p;
	}

}
